package com.yonyou.chuan.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yonyou.chuan.cache.CacheManager;
import com.yonyou.chuan.cache.CacheUtil;
import com.yonyou.chuan.constant.Constant;
import com.yonyou.chuan.crypto.SignHelper;
import com.yonyou.chuan.log.LoggerUtil;

import java.util.HashMap;
import java.util.Map;

public class BipTokenUtil {
    private static final CacheManager CACHEMANAGER = CacheUtil.getCacheManager();
    public static String getAccessToken(String apiUrl, String appKey, String appSecret) throws Exception {
        long timestamp = System.currentTimeMillis();
            String token = CACHEMANAGER.get(Constant.BIP_TOKENKEY);
            if (token != null && !token.isEmpty()) {
                return token;
            }
            // 除签名外的其他参数
            Map<String, Object> params = new HashMap<>();
            params.put("appKey", appKey);
            params.put("timestamp", timestamp);
            // 计算签名
            String signature = SignHelper.sign(params, appSecret);
            params.put("signature", signature);
            // 请求
            com.yonyou.chuan.log.LoggerUtil.printLogger("获取YonBIP AccessToken,请求报文,appKey : {},appSecret : {}", appKey,appSecret);
            String fullPath = apiUrl + "?appKey=" + appKey + "&signature=" + signature + "&timestamp="+ timestamp;
            String resp = HttpUtil.get(fullPath);
            LoggerUtil.printLogger("获取YonBIP AccessToken,响应报文,{} ", resp);
            JSONObject response = JSONUtil.parseObj(resp);
            if(Constant.BIP_SUCCESS_CODE.equals(response.getStr("code"))){
                Integer expire = response.getJSONObject("data").getInt("expire");
                String refreshToken = response.getJSONObject("data").getStr("access_token");
                CACHEMANAGER.put(Constant.BIP_TOKENKEY, refreshToken, expire);
                return refreshToken;
            }
            throw new RuntimeException("获取YonBIP AccessToken,响应失败:" + resp);
    }
}
